package com.xzy.controller;

import com.xzy.config.Audience;
import com.xzy.entity.Project;
import com.xzy.service.ProjectService;
import com.xzy.utils.FileUtils;
import com.xzy.utils.JSONResult;
import com.xzy.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class ProjectController {
    @Autowired
    private ProjectService projectService;

    @Autowired
    private Audience audience;

    @PostMapping("/question/project/add")
    public JSONResult addProject(Project project, HttpServletRequest request) throws ParseException {
          String token = request.getHeader("Authorization");
          String _userId= JWTUtils.getUserId(token,audience.getBase64Secret());
          int userId=Integer.parseInt(_userId);
          project.setUserId(userId);
          String content=project.getProjectContent();
          String url= FileUtils.getUrl(content,userId);
          project.setProjectContent(url);
          projectService.addProject(project);
          return JSONResult.SUCCESS(project);
    }
    @GetMapping("/question/project/getProject/{projectId}")
    public JSONResult getProject(@PathVariable("projectId") int projectId)
    {
        Project project=projectService.getProject(projectId);
        String content=FileUtils.getContent(project.getProjectContent());
        project.setProjectContent(content);
        return JSONResult.SUCCESS(project);
    }
    @GetMapping("/question/project/findAll")
    public JSONResult findAll()
    {
        List<Project> projectList=projectService.findAll();
        for(Project project:projectList)
        {
            String content=FileUtils.getContent(project.getProjectContent());
            project.setProjectContent(content);
        }
        return JSONResult.SUCCESS(projectList);
    }
    @PutMapping("/question/project/update/{projectId}")
    public JSONResult updateProject(Project project,@PathVariable("projectId")int projectId,HttpServletRequest request)
    {
        String token=request.getParameter("token");
        int userId=Integer.parseInt(JWTUtils.getUserId(token,audience.getBase64Secret()));
        project.setUserId(userId);
       // Date projectTime=new Date();
       // project.setProjectTime(projectTime);
        String url=FileUtils.getUrl(project.getProjectContent(),userId);
        project.setProjectContent(url);
        projectService.updateProject(project);
        return JSONResult.SUCCESS(project);
    }
}
